document.addEventListener('DOMContentLoaded', function() {
    // 获取DOM元素
    const searchInput = document.getElementById('search-input');
    const searchBtn = document.getElementById('search-btn');
    const resultCards = document.querySelector('.result-cards');
    
    // 后端API地址
    const API_BASE_URL = 'http://81.69.225.207:5003/api';

    // 搜索按钮点击事件
    searchBtn.addEventListener('click', async function() {
        const searchText = searchInput.value.trim();
        if (!searchText) {
            alert('请输入搜索内容');
            return;
        }
        
        try {
            searchBtn.disabled = true;
            searchBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 搜索中...';
            
            const response = await fetch(`${API_BASE_URL}/video-search/submit`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    query: searchText
                })
            });

            if (!response.ok) {
                throw new Error('搜索请求失败');
            }

            const data = await response.json();
            
            if (data.error) {
                throw new Error(data.error);
            }

            // 清空之前的结果
            resultCards.innerHTML = '';
            
            // 显示搜索结果
            data.results.forEach(video => {
                const videoCard = document.createElement('div');
                videoCard.className = 'video-card';
                videoCard.innerHTML = `
                    <div class="video-info">
                        <h3 class="video-title">${video.title}</h3>
                        <p class="video-duration">${video.duration}</p>
                        <a href="${video.url}" target="_blank" class="watch-btn">
                            <i class="fas fa-play"></i> 观看视频
                        </a>
                    </div>
                `;
                resultCards.appendChild(videoCard);
            });

            if (data.results.length === 0) {
                resultCards.innerHTML = `
                    <div class="no-results">
                        <i class="fas fa-search"></i>
                        <p>未找到相关视频</p>
                    </div>
                `;
            }

        } catch (error) {
            console.error('视频搜索失败:', error);
            resultCards.innerHTML = `
                <div class="error-message">
                    <i class="fas fa-exclamation-circle"></i>
                    <p>${error.message || '搜索失败，请稍后重试'}</p>
                </div>
            `;
        } finally {
            searchBtn.disabled = false;
            searchBtn.innerHTML = '<i class="fas fa-search"></i> 搜索视频';
        }
    });

    // 回车键触发搜索
    searchInput.addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            searchBtn.click();
        }
    });
}); 